<?php
require_once "./vendor/autoload.php";

use \PhpAmqpLib\Connection\AMQPStreamConnection;

class Base
{
    public static $conf = [
        'host' => '127.0.0.1',
        'port' => 5672,
        'user' => 'guest',
        'pwd' => 'guest',
        'vhost' => '/',
    ];


    /**
     * @var PhpAmqpLib\Connection\AMQPStreamConnection
     * 链接对象 mq之间的连接
     */
    public $conn = null; //

    /**
     * @var PhpAmqpLib\Channel\AMQPChannel
     * 在已连接基础上建立生产者与mq之间的通道
     */
    public $channel = null;

    public function __construct()
    {
        $conf = self::$conf;
        //建立生产者与mq之间的连接
        $this->conn = new AMQPStreamConnection($conf['host'], $conf['port'], $conf['user'], $conf['pwd'], $conf['vhost']);
        $this->channel = $this->conn->channel();
    }

    /**
     * @param $exchangeName string 交换机名称
     * @param $type string 路由类型   direct精准推送; fanout 广播。推送到绑定到此交换机下的所有队列;  topic组播。比如上面我绑定的关键字是sms_send，那么他可以推送到*.sms_send的所有队列 headers这个目前不知道是如何推送的
     * @param $passive bool 默认false
     * @param $durable bool 交换机是否开启持久化
     * @param $auto_delete bool 通道关闭后是否删除交换机
     * 创建交换机 初始化交换机
     */
    public function exchangeDeclare($exchangeName, $type = 'direct', $passive = false, $durable = true, $auto_delete = false)
    {
        //声明初始化交换机 创建交换机
        $this->channel->exchange_declare($exchangeName, $type, $passive, $durable, $auto_delete);

    }

    /**
     * @param string $queueName 队列机名称
     * @param bool $passive
     * @param bool $durable 队列是否开启持久化
     * @param bool $exclusive
     * @param bool $auto_delete 通道关闭后是否删除队列
     * 创建队列
     */
    public function queueDeclare($queueName, $passive = false, $durable = true, $exclusive = false, $auto_delete = false)
    {
        $this->channel->queue_declare($queueName, false, true, false, false); //声明初始化一条队列
    }

    /**
     * @param string $queueName 队列名称
     * @param string $exchangeName 交换机名称
     * @param string $routingKey 路由关键字
     * 队列绑定到交换机上
     */
    public function queueBind($queueName, $exchangeName, $routingKey)
    {
        //将队列与某个交换机进行绑定，并使用路由关键字
        $this->channel->queue_bind($queueName, $exchangeName, $routingKey);
    }

    /**
     * @throws Exception
     * 关闭链接
     */
    public function close()
    {
        $this->conn->close();
        $this->channel->close();
    }


}
